<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta charset="utf-8" />
	<title>TIMS map implementation</title>
	<meta name="generator" content="EverEdit" />
	<meta name="author" content="" />
	<meta name="keywords" content="" />
	<meta name="description" content="" />

	<!--ESRI Import-->
	<link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/library/3.11/3.11/esri/css/esri.css"/>
	<link rel="stylesheet" href="http://localhost:8080/arcgis_js_api/library/3.11/3.11/dijit/themes/claro/claro.css">
	
	<script type="text/javascript" src="http://localhost:8080/arcgis_js_api/library/3.11/3.11/init.js"></script>


	<!--link rel="stylesheet" href="http://js.arcgis.com/3.11/esri/css/esri.css"-->
    <!--script src="http://js.arcgis.com/3.11/"></script-->

	<!--EasyUI import-->
	<link rel="stylesheet" type="text/css" href="jquery-easyui-1.4.1/themes/default/easyui.css">
	<link rel="stylesheet" type="text/css" href="jquery-easyui-1.4.1/themes/icon.css">
	<script type="text/javascript" src="jquery-easyui-1.4.1/jquery.min.js"></script>
	<script type="text/javascript" src="jquery-easyui-1.4.1/jquery.easyui.min.js"></script>

    
	<!--Customization Function-->
	<script type="text/javascript">
	<!--
		var djConfig = {parseOnLoad:true};
	//-->
	</script>
	<script type="text/javascript">
	<!--
		//dojo.require('esri.map');
		dojo.require('esri.dijit.Scalebar');
		dojo.require('esri.dijit.OverviewMap');

		//dojo.require(['esri/toolbars/draw', 'esri/graphic', 'esri/symbols/SimpleMarkerSymbol', 'esri/symbols/SimpleLineSymbol', 'esri/symbols/SimpleFillSymbol']);
		dojo.require('esri.toolbars.draw');
		dojo.require('esri.graphic');
		dojo.require('esri.symbols.SimpleMarkerSymbol');
		dojo.require('esri.symbols.SimpleLineSymbol');
		dojo.require('esri.symbols.SimpleFillSymbol');
		

		var map;
		var toolbar;
		function init() {
			//var startExtent = new esri.geometry.Extent(114.15741889272611, 22.44699909259, 114.17348501343749, 22.451110801208078, new esri.SpatialReference({wkid:4326}));
			var startExtent = new esri.geometry.Extent(113.824635, 22.571855, 114.480559, 22.138010, new esri.SpatialReference({wkid:4326}));
			//var lods = [{'level': 0, 'resolution': 0.00004758922, 'scale': 2000},{'level': 1, 'resolution': 0.00002379461, 'scale': 1000},{'level': 2, 'resolution': 0.0000118973, 'scale': 500},{'level': 3, 'resolution': 0.00000475892, 'scale': 200},{'level': 4, 'resolution': 0.00000237946, 'scale': 100}];
			
			// var mapOption = {nav:true, slider:true, extent: startExtent, lods: lods};
			var mapOption = {nav:true, slider:true, sliderStyle:'large', extent: startExtent};
			
			map = new esri.Map('mapDiv', mapOption);

			//var dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer('http://10.187.203.178:6080/arcgis/rest/services/HK_TEXT2/MapServer');
			var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer('http://10.187.203.178:6080/arcgis/rest/services/HK_TEXT2/MapServer');

			//map.addLayer(dynamicMapServiceLayer);
			map.addLayer(tiledMapServiceLayer);

			dojo.connect(map, 'onLoad', function() {
				dojo.connect(map, 'onMouseMove', showCoordinates);
				dojo.connect(map, 'onMouseDrag', showCoordinates);
				var scalebar = new esri.dijit.Scalebar({map:map, scalebarUnit:'english', attachTo:"bottom-left"});

				// add the overview map
				var overviewMapDijit = new esri.dijit.OverviewMap({
					map: map,
					visible:true
				});
				overviewMapDijit.startup();

				afterMapInit();

				createToolbar();

			});
		}

		function afterMapInit() {
			// Add labels to slider start
			var labels = [];
	        var lods = map.__tileInfo.lods;
	        for (var i=0, il=lods.length; i<il; i++) {
	          labels[i] = lods[i].scale;
	        }

	        esriConfig.defaults.map.sliderLabel = {
	          tick: 2,
	          labels: labels,
	          style: "width:2em; font-family:Verdana; font-size:65%; color:#fff; padding-left:2px;"
	        };
	        // Add labels to slider end
		}

		function showCoordinates(event) {
			var mp=event.mapPoint;
            var mp2=event.screenPoint;
            dojo.byId("info2").innerHTML="地理坐标："+mp.x+","+mp.y+"<br/>屏幕坐标："+mp2.x+","+mp2.y;
		}

		function activeTool(tool) {
			toolbar.activate(esri.toolbars.Draw[tool]);
			map.hideZoomSlider();
		}

		function createToolbar() {
			toolbar = new esri.toolbars.Draw(map);
			toolbar.on('draw-end', add2map);
		}

		function add2map(evt) {
			var symbol;
			toolbar.deactivate();
			map.showZoomSlider();
			switch(evt.geometry.type) {
				case 'point':
				case 'multipoint':
					symbol = new esri.symbols.SimpleMarkerSymbol();
					break;
				case 'polyline':
					symbol = new esri.symbols.SimpleLineSymbol();
					break;
				default:
					symbol = new esri.symbols.SimpleFillSymbol();
					break;
			}

			var graphic = new esri.Graphic(evt.geometry, symbol);
			map.graphics.add(graphic);
		}

		// 测距
		dojo.require('dojo._base.lang');
		dojo.require('dojo.json');
		dojo.require('esri.dijit.Measurement');
		dojo.require('esri.symbols.SimpleFillSymbol');
		dojo.require('esri.symbols.SimpleLineSymbol');
		dojo.require('esri.Color');
		dojo.require("esri.tasks.DistanceParameters");
		dojo.require('esri.tasks.AreasAndLengthsParameters');

		var units;
		var endGraphic;
		var geometryService;
		var totalDistance = 0, inputPoints = [], legDistance = [];

		geometryService = new esri.tasks.GeometryService("http://10.187.203.178:6080/arcgis/rest/services/Utilities/Geometry/GeometryServer");
		
		var measuringSfs = new esri.symbols.SimpleFillSymbol('solid', new esri.symbols.SimpleLineSymbol("solid", new esri.Color([195, 176, 23]), 2), null);

		function mapDistanceHandler(evt) {
			var inPoint = new esri.geometry.Point(evt.mapPoint.x, evt.mapPoint.y, map.spatialReference);
			inputPoints.push(inPoint);

			// Define the symbology for the graphics
			var markerSymbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 12, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([204, 102, 51]), 1), new dojo.Color([158, 184, 71, 0.65]));
			var polylineSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([204, 102, 51]), 4);
			var font = new esri.symbol.Font("18px", esri.symbol.Font.STYLE_NORMAL, esri.symbol.Font.VARIANT_NORMAL, esri.symbol.Font.WEIGHT_BOLDER);
			var textSymbol;
			if (inputPoints.length === 1) { //start location label
	          textSymbol = new esri.symbol.TextSymbol("Start", font, new dojo.Color([204, 102, 51]));
	          textSymbol.yoffset = 8;
	          map.graphics.add(new esri.Graphic(evt.mapPoint, textSymbol));
	        }

	        if (inputPoints.length >= 2) { //end location label
	          textSymbol = new esri.symbol.TextSymbol("Finish", font, new dojo.Color([204, 102, 51]));
	          textSymbol.yoffset = 8;
	          if (endGraphic) { //if an end label already exists remove it
	              map.graphics.remove(endGraphic);
	          }
	          endGraphic = new esri.Graphic(evt.mapPoint, textSymbol);
	          map.graphics.add(endGraphic);
	        }
	        // add a graphic for the clicked location
	        map.graphics.add(new esri.Graphic(evt.mapPoint, markerSymbol));

			// if there are two input points call the geometry service and perform the distance operation
			if (inputPoints.length >= 2) {
	          dojo.style(dojo.byId("distanceDetails"), "display", "block");
	          var distParams = new esri.tasks.DistanceParameters();
	          distParams.distanceUnit = esri.tasks.GeometryService.UNIT_STATUTE_MILE;

	          distParams.geometry1 = inputPoints[inputPoints.length - 2];
	          distParams.geometry2 = inputPoints[inputPoints.length - 1];
	          distParams.geodesic = true;

	          //draw a polyline to connect the input points
	          var polyline = new esri.geometry.Polyline(map.spatialReference);
	          polyline.addPath([distParams.geometry1, distParams.geometry2]);
	          map.graphics.add(new esri.Graphic(polyline, polylineSymbol));
	          //Calculate the geodesic distance 
	          geometryService.distance(distParams, function(distance) {
	            if (isNaN(distance)) {
	                distance = 0;
	            }
	            legDistance.push(dojo.number.format(distance, {
	                places: 2
	            }));
	            totalDistance += distance;
	            var content = "";
	            dojo.forEach(legDistance, function(leg, index) {
	                content = content + "<b>Leg " + (index + 1) + "</b>" + ": " + leg + "<br />";
	            });
	            content = content + "<b>Total:</b> " + dojo.number.format(totalDistance, {
	                places: 2
	            }) + " miles <br />";
	            dojo.byId('distanceDetails').innerHTML = content;
	          });
	        }

		}

		var distanceHandler;
		var tb;
		function measureTool(type, enable) {
			geometryService.on("areas-and-lengths-complete", outputAreaAndLength);
			if(!tb) {
				tb = new esri.toolbars.Draw(map);
			}
			if(enable) {
				if('DISTANCE' == type) {
					distanceHandler = dojo.connect(map, "onClick", mapDistanceHandler);
				}
				if('AREA' == type) {
					tb.on("draw-end", dojo._base.lang.hitch(map, getAreaAndLength));
					tb.activate(esri.toolbars.Draw.FREEHAND_POLYGON);
				}
			} else {
				if('DISTANCE' == type) {
					dojo.disconnect(distanceHandler);
					map.graphics.clear();
			        inputPoints.length = 0;
			        totalDistance = 0;
			        legDistance.length = 0;
			        dojo.byId("distanceDetails").innerHTML = "";
			        dojo.style(dojo.byId("distanceDetails"), "display", "none");

				}
				if('AREA' == type) {
					tb.deactivate();
					map.graphics.clear();
				}
			}
		}


		// 测量面积
		function getAreaAndLength(evtObj) {
	      var geometry = evtObj.geometry;
	      map.graphics.clear();
	      
	      var graphic = map.graphics.add(new esri.Graphic(geometry, new esri.symbols.SimpleFillSymbol()));
	      
	      //setup the parameters for the areas and lengths operation
	      var areasAndLengthParams = new esri.tasks.AreasAndLengthsParameters();
	      areasAndLengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_FOOT;
	      areasAndLengthParams.areaUnit = esri.tasks.GeometryService.UNIT_ACRES;
	      areasAndLengthParams.calculationType = "geodesic";
	      geometryService.simplify([geometry], function(simplifiedGeometries) {
	        areasAndLengthParams.polygons = simplifiedGeometries;
	        geometryService.areasAndLengths(areasAndLengthParams);
	      });
	    }

	    function outputAreaAndLength(evtObj) {
		    var result = evtObj.result;
		    alert(result.areas[0].toFixed(3) + 'acres');
	    }

	    // 地图基本操作（缩放、平移）
	    dojo.require("esri.toolbars.navigation");
	    var toolbarNav;

	    function mapNavigation(tool) {
		    if(!toolbarNav) {
			    toolbarNav = new esri.toolbars.Navigation(map);
		    }
		    switch(tool) {
			    case 'zoomin':
				    toolbarNav.activate(esri.toolbars.Navigation.ZOOM_IN);
				    break;
				case 'zoomout':
					toolbarNav.activate(esri.toolbars.Navigation.ZOOM_OUT);
				    break;
				case 'pan':
					toolbarNav.activate(esri.toolbars.Navigation.PAN);
				    break;
				case 'fullextent':
					toolbarNav.zoomToFullExtent();
					break;
				    
		    }
	    }

	    // 添加标注图层（点）
	    dojo.require('esri.InfoTemplate');
	    function addPic() {
		    var picSymbol = new esri.symbol.PictureMarkerSymbol('img4demo/car.gif', 24, 22);
		    var picPosition = new esri.geometry.Point(114.2000, 22.4444, map.spatialReference);
		    var infoTemplate = new esri.InfoTemplate('TestPic1', '<iframe src="http://www.sogou.com" scrolling="no" frameBorder="no"></iframe>');
		    var picGraphic = new esri.Graphic(picPosition, picSymbol, {bizId: 'testPic001'}, infoTemplate);

		    var picPosition2 = new esri.geometry.Point(114.2723, 22.4523, map.SpatialReference);
		    var infoTemplate2 = new esri.InfoTemplate('TestPic1', '<iframe src="http://www.sogou.com" scrolling="no" frameBorder="no"></iframe>');
		    var picGraphic2 = new esri.Graphic(picPosition2, picSymbol, {bizId: 'testPic002'},infoTemplate2);
		    

		    var picLayer = new esri.layers.GraphicsLayer({id:'picLayer'});
			picLayer.add(picGraphic);
			picLayer.add(picGraphic2);

		    //dojo.connect(picLayer, 'onClick', function(e){alert('You clicked the graphic[' + e.graphic.geometry.x + ',' + e.graphic.geometry.y + '], this is [' + e.graphic.attributes.bizId + ']');});
		    map.addLayer(picLayer);
	    }

	    // 添加标注图层（线）
	    dojo.require('esri.geometry.Polyline');
	    function addCustLine() {
		    var linePoint1 = new esri.geometry.Point(114.2000, 22.4444, map.spatialReference);
		    var linePoint2 = new esri.geometry.Point(114.2386, 22.4523, map.spatialReference);
		    var linePoint3 = new esri.geometry.Point(114.2723, 22.4424, map.spatialReference);
		    var line = new esri.geometry.Polyline(map.spatialReference);
		    line.addPath([linePoint1, linePoint2, linePoint3]);

		    var lineSymbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,0,0,0.5]),3);

		    var lineLayer = new esri.layers.GraphicsLayer({id:'lineLayer'});
		    lineLayer.add(new esri.Graphic(line, lineSymbol));

		    map.addLayer(lineLayer);
	    }

	    // 图片隐藏/显示
	    function picLayerShow(visible) {
		    if(visible) {
			    map.getLayer('picLayer').show();
		    } else {
			    map.getLayer('picLayer').hide();
		    }
	    }

	    function picLayerShowOrHide() {
		    var myLayer = map.getLayer('picLayer');
		    if(!myLayer) {
			    return;
		    }
		    if(myLayer.visible) {
			    myLayer.hide();
		    } else {
			    myLayer.show();
		    }

		    // cascade with layer tree
		    manageLayerTreeNode('picLayer', myLayer.visible);
	    }

	    // 线图层显示/隐藏
	    function lineLayerShowOrHide() {
		    var myLayer = map.getLayer('lineLayer');
		    if(!myLayer) {
			    return;
		    }
		    if(myLayer.visible) {
			    myLayer.hide();
		    } else {
			    myLayer.show();
		    }

			// cascade with layer tree
		    manageLayerTreeNode('lineLayer', myLayer.visible);
	    }

	    // 图层的显示与隐藏
	    function layerControl(){
		    var layerData = [{"id":1,"text":"TIMS Map Layers","children":[{"id":"picLayer","text":"picLayer","checked":"true"},{"id":"lineLayer","text":"lineLayer","checked":"true"}]}];
			$('#layerTree').tree({
				data: layerData,
				checkbox: true,
				onCheck:function(node, checked) {
					var myLayer = map.getLayer(node.id);
					if(myLayer) {
						if(checked) {
							myLayer.show();
						} else {
							myLayer.hide();
						}
					}
				}
			}
			);
		}

		function manageLayerTreeNode(layerId, visible) {
			var layerNode = $('#layerTree').tree('find', layerId);
			if(layerNode) {
				if(visible) {
					$('#layerTree').tree('check', layerNode.target);
				} else {
					$('#layerTree').tree('uncheck', layerNode.target);
				}
			}
		}

		// 查找点
		function findGraphicByBizId(bizId) {
			var myLayer = map.getLayer('picLayer');
			if(myLayer) {
				var graphics = myLayer.graphics;
				if(graphics) {
					for(var idx in graphics) {
						var myGraphic = graphics[idx];
						if(myGraphic.attributes.bizId == bizId) {
							return myGraphic;
						}
					}
				}
			}
		}

		function picMove(bizId) {
			var myGraphic = findGraphicByBizId(bizId);
			if(!myGraphic) {
				return;
			}

			var x = myGraphic.geometry.x;
			var y = myGraphic.geometry.y;
			var rand = Math.random()/100;
			var newPosition = new esri.geometry.Point(x + rand, y + rand, map.spatialReference);
			myGraphic.geometry = newPosition;

			var myLayer = map.getLayer('picLayer');
			if(myLayer) {
				myLayer.redraw();
			}
		}
		
		// Start the init method
		dojo.addOnLoad(init);
	//-->
	</script>

	<!--Customization Style-->
	<style>
		html, body, #mapDiv {
			padding:0;
			margin:0;
			height:100%;
		}
	</style>
</head>
<body class="claro">
	<div id="mapDiv"></div>
	<div id="iToolbar" style="position: absolute; left: 100px; top: 10px; z-index: 777; width:900px; height:100px;">
		<button onclick="mapNavigation('zoomin')">放大</buton>
		<button onclick="mapNavigation('zoomout')">缩小</buton>
		<button onclick="mapNavigation('pan')">平移</buton>
		<button onclick="mapNavigation('fullextent')">全幅显示</buton>
		<button onclick="activeTool('POINT')">画点</buton>
		<button onclick="activeTool('LINE')">画直线</buton>
		<button onclick="activeTool('POLYLINE')">画折线</buton>
		<button onclick="activeTool('TRIANGLE')">画三角形</buton>
		<button onclick="activeTool('CIRCLE')">画圆</buton>
		<button onclick="activeTool('ELLIPSE')">画椭圆</buton>
		<button onclick="measureTool('DISTANCE', true)">测距</buton>
		<button onclick="measureTool('DISTANCE', false)">取消测距</buton>
		<button onclick="measureTool('AREA', true)">测面积</buton>
		<button onclick="measureTool('AREA', false)">取消测面积</buton>
	</div>

	<div id="iToolbar" style="position: absolute; left: 100px; top: 40px; z-index: 777; width:900px; height:100px;">
		<button onclick="addPic()">添加图片</buton>
		<button onclick="addCustLine()">添加线</buton>
		<button onclick="picLayerShowOrHide()">图片显示/隐藏</button>
		<button onclick="lineLayerShowOrHide()">线显示/隐藏</button>
		<button onclick="layerControl()">图层控制</button>
		<button onclick="picMove('testPic001')">移动点标注</button>
	</div>

	<div id="iLayers" class="easyui-panel" style="padding:5px; position: absolute; left: 1000px; top: 10px; width: 200px; height: 100px; z-index: 777" >
		<ul id="layerTree" class="easyui-tree"></ul>
	</div>
	
	<!--<div id="scaleBarDiv" style="position: absolute; bottom:20px; left:20px;">123</div>-->
	<div id="info">info</div>
	<div id="info2">info2</div>
	<div id="distanceDetails">distance</div>
</body>
</html>
